import Vue from 'vue';
import store from '../../../index'
import SDK from '../../../../assets/js/im/NIM_Web_SDK_v7.5.0';
import WebRTC from '../../../../assets/js/im/NIM_Web_WebRTC_v7.5.0';
SDK.NIM.use(WebRTC);
import MD5 from "js-md5";
export default {
    chatMsg (state, obj) {
        let currentUser = store.getters.currentUserFn;
        let currentThird = store.getters.currentThirdFn;
        let currentStore = store.getters.currentStoreFn;
        let url = `${Vue.prototype.NW_API_API_LOCALE_VERSION}/customer/service/last/unread/message`;
        let params = {
            storeId: obj.storeId,
            userId: currentUser && currentUser.userId ? currentUser.userId : 0,
            thirdId: currentThird && currentThird.thirdId ? currentThird.thirdId : 0,
        }
        /*   ? storeId：                            ----店铺ID
            & userId：                          ----用户ID，没有不传或传0
            & thirdId：                         ----第三方ID，没有不传或传0*/
        /*每过3秒去调一次接口*/
        setInterval(() => {
            if ((currentStore && currentStore.storeId == obj.storeId) || !currentStore) {
                Vue.prototype.xurl.get(url, params).then((data) => {
                    if (data.success) {
                        let content = '';
                        if (data.result) {
                            switch (data.messageType) {
                                case 0:
                                    content = data.result.content || "收到一条信息";
                                    break;
                                case 1:
                                    content = "收到一张图片";
                                    break;
                                case 2:
                                    content = "收到一条语音";
                                    break;
                                case 3:
                                    content = "收到一个视频";
                                    break;
                                case 4:
                                    content = "收到一个定位信息";
                                    break;
                                case 5:
                                    content = "收到一个红包";
                                    break;
                                case 6:
                                    content = "收到转账信息";
                                    break;
                                default:
                                    content = data.result.content;
                                    break;
                            }
                        }
                        /*
                        *   "customerType": 1,      -------客服角色类型3-店长   5-员工  6-虚店长
                            "customerKey": 1,       -------客服角色ID
                            "messageType": 1,       ---------消息类型（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)
                            "content": "态度极差"   ---------发送的内容*/
                        state.notReadMsg = Object.assign({}, { content })

                    }
                });
            }
        }, 3000)
    },
    /*登录聊天室*/
    createNeplayerRoom (state, obj) {
        let currentUser = store.getters.currentUserFn;
        let currentThird = store.getters.currentThirdFn;
        if (!((currentUser && currentUser.userId) || (currentThird && currentThird.thirdId))) {
            return false;
        }
        let that = this;
        let sessionData = [];
        let account = (currentUser && currentUser.chatAccount ? currentUser.chatAccount : '') || (currentThird && currentThird.chatAccount ? currentThird.chatAccount : '');
        let password = MD5(account + 'ybt').toUpperCase();
        let chatRoomId = store.state.api.playChannelMsg.chatRoomId
        let nim = SDK.NIM.getInstance({
            onupdatesession: onUpdateSession,//更新会话列表
            onsessions: onSessions,//会话列表
            appKey: Vue.prototype.CHATAPPKEY,//appkey
            account: account,//账号
            token: password,//密码
            onconnect: () => {
                state.groupChat.nim = nim;
                window.sessionStorage.setItem('groupChat', state.groupChat.nim);
                if (obj && obj.getChatRoomObj) {
                    that.commit('getChatRoomAddress', obj.getChatRoomObj)
                }
                if (obj && obj.getChatroomMsg) {
                    that.commit('getChatroomMsg', obj.getChatroomMsg)
                }
                if (obj && obj.getChatRoomAddress) {
                    that.commit('getChatRoomAddress')
                }
                if (chatRoomId && currentUser.userId) {
                    let tempEnterObj = {
                        userId: currentUser.userId,
                        roomId: chatRoomId
                    }
                    that.commit('enterChatRoom', tempEnterObj);
                }
                if (obj && obj.connentSuccess && typeof obj.connentSuccess == 'function') {
                    obj.connentSuccess();
                }
            },//连接成功
            onwillreconnect: () => {
                console.log("group chat onwillreconnect")
            },//即将重连
            ondisconnect: () => {
                console.log("group chat ondisconnect22")
            },//连接失败
            onerror: () => {
                console.log("group chat onerror")
            },//出错
            onDisconnect: () => {
                console.log("group chat onDisconnect11")
            },//
            onsyncdone: function (msg) {
                // 初始化音视频
                // that.commit('initWebrtc')
            },
            onmsg: groupChatOnMsg,//接收消息
        });

        function onUpdateSession (session) {
            let data = JSON.parse(window.localStorage.getItem("sessionData"))
            sessionData = nim.mergeSessions(data, session);
            // 移动端会丢失数据需要存在本地
            window.localStorage.setItem("sessionData", JSON.stringify(sessionData));
            // console.log(sessionData, '更新会话列表');
            that.commit('getSessionList', sessionData)
        }

        function onSessions (sessions) {
            // console.log('获取会话列表', sessions);
            // 移动端会丢失数据需要存在本地
            window.localStorage.setItem("sessionData", JSON.stringify(sessions));

            sessionData = nim.mergeSessions(sessionData, sessions);
            that.commit('getSessionList', sessions)
        }

        function groupChatOnMsg (getMsg) {
            // console.log(getMsg,'收到消息啦');

            state.hintList = window.sessionStorage.getItem('hintList') ? JSON.parse(window.sessionStorage.getItem('hintList')) : []
            state.hintList.unshift(getMsg)
            window.sessionStorage.setItem('hintList', JSON.stringify(state.hintList))
        }
    },
    /*登录和获取聊天室地址房间*/
    async getChatRoomAddress (state, getChatRoomObj) {
        let chatroom;
        let that = this;
        let getterGroupIm = that.getters.getterGroupIm;
        let currentUser = store.getters.currentUserFn;
        let currentThird = store.getters.currentThirdFn;
        let chatRoomId = store.state.api.playChannelMsg.chatRoomId;
        let chatroomNick = '游客';
        if (currentUser && currentUser.userName) {
            chatroomNick = currentUser.userName;
        } else if (currentThird && (currentThird.nickName || currentThird.userName)) {
            chatroomNick = currentThird.nickName;
            if (currentThird.userName) {
                chatroomNick = currentThird.nickName;
            }
        }
        if (/^1\d{10}$/ig.test(Number(chatroomNick)) && chatroomNick.toString().length == 11) {
            chatroomNick = chatroomNick.toString().slice(0, 3) + '****' + chatroomNick.toString().slice(-4);
        }
        if ((currentUser && currentUser.userId) || (currentThird && currentThird.thirdId)) {
            getterGroupIm.getChatroomAddress({
                chatroomId: chatRoomId,
                done: getChatroomAddressDone
            });
        } else {
            await this.commit('getChatRoom', { roomId: chatRoomId })
            let address = []
            /*先退出出聊天室*/
            try {
                address = store.state.api.chatroomMsg.addrPool['1'];
            } catch (e) {
                Vue.$toast({ message: '连接聊天室失败' });
                return;
            }
            state.groupChat.chatRoom = SDK.Chatroom.getInstance({
                appKey: Vue.prototype.CHATAPPKEY,
                chatroomId: chatRoomId,
                chatroomAddresses: address,
                chatroomNick: chatroomNick,
                chatroomAvatar: currentThird && currentThird.photoUrl ? currentThird.photoUrl : Vue.prototype.staticImageUrl('images/look/default_userheader.png'),
                isAnonymous: true,
                onconnect: () => {
                    if (getChatRoomObj && getChatRoomObj.getChatroomMsg) {
                        that.commit('getChatroomMsg', getChatRoomObj)
                    }
                    if (getChatRoomObj && getChatRoomObj.getChatroomMembers) {
                        that.commit('getChatroomMembers', getChatRoomObj)
                    }
                    window.sessionStorage.setItem('chatRoom', state.groupChat.chatRoom);
                },
                onerror: () => console.log('onerror'),
                onwillreconnect: () => console.log('onwillreconnect'),
                ondisconnect: () => console.log('ondisconnect'),
                // 消息
                onmsgs: onChatroomMsgs
            });
        }

        function getChatroomAddressDone (error, obj) {
            let account = (currentUser && currentUser.chatAccount ? currentUser.chatAccount : '') || (currentThird && currentThird.chatAccount ? currentThird.chatAccount : '');
            /*这里只用用户登录*/
            // let account = currentUser && currentUser.chatAccount ? currentUser.chatAccount : '';
            let password = MD5(account + 'ybt').toUpperCase();
            let chatroomAvatar = Vue.prototype.staticImageUrl('images/look/default_userheader.png')
            if (currentThird && currentThird.photoUrl) {
                chatroomAvatar = currentThird.photoUrl;
            }
            if (currentUser && currentUser.photoUrl) {
                chatroomAvatar = currentUser.photoUrl;
            }
            if (account && !state.groupChat.chatRoom || (state.groupChat.chatRoom && !state.groupChat.chatRoom.account)) {
                state.groupChat.chatRoom = SDK.Chatroom.getInstance({
                    appKey: Vue.prototype.CHATAPPKEY,
                    account: account,
                    token: password,
                    chatroomId: chatRoomId,
                    chatroomNick: chatroomNick,
                    chatroomAvatar: chatroomAvatar,
                    chatroomAddresses: obj.address,
                    onconnect: () => {
                        let tempEnterObj = {
                            userId: currentUser.userId,
                            roomId: chatRoomId
                        }
                        that.commit('enterChatRoom', tempEnterObj);
                        if (getChatRoomObj && getChatRoomObj.getChatroomMsg) {
                            setTimeout(() => {
                                that.commit('getChatroomMsg', getChatRoomObj)
                            }, 10)
                        }
                        if (getChatRoomObj && getChatRoomObj.getChatroomMembers) {
                            setTimeout(() => {
                                that.commit('getChatroomMembers', getChatRoomObj)
                            }, 10)
                        }
                        window.sessionStorage.setItem('chatRoom', state.groupChat.chatRoom);
                    },
                    onerror: () => console.log('onerror'),
                    onwillreconnect: () => console.log('onwillreconnect'),
                    ondisconnect: () => console.log('ondisconnect'),
                    // 消息
                    onmsgs: onChatroomMsgs
                });
            } else {
                let tempEnterObj = {
                    userId: currentUser.userId,
                    roomId: chatRoomId
                }
                that.commit('enterChatRoom', tempEnterObj);
                if (getChatRoomObj && getChatRoomObj.getChatroomMsg) {
                    setTimeout(() => {
                        that.commit('getChatroomMsg', getChatRoomObj)
                    }, 10)
                }
                if (getChatRoomObj && getChatRoomObj.getChatroomMembers) {
                    setTimeout(() => {
                        that.commit('getChatroomMembers', getChatRoomObj)
                    }, 10)
                }
            }
        }

        function onChatroomMsgs (obj) {
            let tempObj = {}
            if (Array.isArray(obj) && obj.length > 0) {
                obj.forEach((value, index) => {
                    if (value.type == 'notification' && value.attach && value.attach.type == 'memberEnter') {
                        if (value.attach.fromNick) {
                            tempObj = { userName: value.attach.fromNick };
                            that.commit('personEnter', tempObj);
                        }
                    }
                })
            }
            if (getChatRoomObj.success) {
                getChatRoomObj.success(obj)
            }
            if (getChatRoomObj && getChatRoomObj.getChatroomMsg) {
                setTimeout(() => {
                    that.commit('getChatroomMsg', getChatRoomObj)
                }, 10)
            }
            if (getChatRoomObj && getChatRoomObj.getChatroomMembers) {
                setTimeout(() => {
                    that.commit('getChatroomMembers', getChatRoomObj)
                }, 10)
            }
        }
    },
    getChatroomMsg (state, obj) {
        state.groupChat.chatRoom.getChatroom({
            done: getChatroomDone
        });

        function getChatroomDone (error, getChatroomDoneObj) {
            console.log('获取聊天室信息' + (!error ? '成功' : '失败'), error, getChatroomDoneObj);
            if (obj && obj.getChatroomMsg) {
                obj.getChatroomMsg(getChatroomDoneObj);
            }
        }
    },
    getChatroomMembers (state, obj) {
        let guest = false;
        let notGuest = false;
        let tempObj = { members: [] };
        state.groupChat.chatRoom.getChatroomMembers({
            guest: true,//是否为游客
            limit: 100,
            done: getChatroomGuest
        });
        state.groupChat.chatRoom.getChatroomMembers({
            guest: false,//是否为游客
            limit: 100,
            done: getChatroomMembers
        });

        function getChatroomGuest (error, getChatroomDoneObj) {
            console.log('获取获取游客' + (!error ? '成功' : '失败'), error, getChatroomDoneObj);
            guest = true;
            if (getChatroomDoneObj && getChatroomDoneObj.members && getChatroomDoneObj.members.length > 0) {
                tempObj.members.push(...getChatroomDoneObj.members);
            }
            if (notGuest) {
                if (obj && obj.getChatroomMembers) {
                    let tempMemberObj = Object.assign({}, getChatroomDoneObj, tempObj);
                    obj.getChatroomMembers(tempMemberObj);
                }
            }
        }

        function getChatroomMembers (error, getChatroomDoneObj) {
            console.log('获取普通成员' + (!error ? '成功' : '失败'), error, getChatroomDoneObj);
            notGuest = true;
            if (getChatroomDoneObj && getChatroomDoneObj.members && getChatroomDoneObj.members.length > 0) {
                tempObj.members.push(...getChatroomDoneObj.members);
            }
            if (guest) {
                if (obj && obj.getChatroomMembers) {
                    let tempMemberObj = Object.assign({}, getChatroomDoneObj, tempObj);
                    obj.getChatroomMembers(tempMemberObj);
                }
            }

        }
    },
    sendGroupMsg (state, obj) {
        state.groupChat.chatRoom.sendText({
            text: obj.text,
            done: sendMsgDone,
        });

        function sendMsgDone (error, msg) {
            console.log('发送聊天室' + msg.type + '消息' + (!error ? '成功' : '失败') + ', id=' + msg.idClient, error, msg);
            if (obj.success) {
                obj.success(msg);
            }
        }
    },
    personEnter (state, obj) {
        let currentUser = store.getters.currentUserFn;
        let currentThird = store.getters.currentThirdFn;
        let photoUrl = (currentUser && currentUser.photoUrl) || (currentThird && currentThird.photoUrl)
        let userName = (currentUser && currentUser.userName) || (currentThird && currentThird.userName)
        if (obj && obj.userName) {
            userName = obj && obj.userName ? obj.userName : userName;
            if (/^1\d{10}$/ig.test(Number(userName)) && userName.toString().length == 11) {
                userName = userName.toString().slice(0, 3) + '****' + userName.toString().slice(-4);
            }
        }
        state.groupChat.enterPersonMsg = {
            photoUrl: obj && obj.photoUrl ? obj.photoUrl : photoUrl,
            userName: userName,
            userId: obj && obj.userId ? obj.userId : currentUser && currentUser.userId,
            thirdId: obj && obj.thirdId ? obj.thirdId : currentThird && currentThird.thirdId,
        }
        if (state.groupChat.enterPersonMsg && Object.keys(state.groupChat.enterPersonMsg).length > 0) {
            setTimeout(() => {
                state.groupChat.enterPersonMsg = {};
            }, 2000)
        }
    },
    async discountRoom () {
        let currentUser = store.getters.currentUserFn;
        let currentThird = store.getters.currentThirdFn;
        if (!(currentUser && currentUser.userId) && !(currentThird && currentThird.thirdId)) {
            try {
                let visitorIsLogin = this.getters.getterChatRoom;
                await visitorIsLogin.disconnect();
                await window.sessionStorage.setItem('chatRoom', false);
                state.groupChat.chatRoom = false
            } catch (e) {
            }
        }
    },
    // 获取会话列表
    async getSessionList (state, obj) {
        let arr = []
        let data = obj.map((SessionItem) => {
            return {
                to: SessionItem.to,
                time: SessionItem.updateTime,
                from: SessionItem.lastMsg.from,
                text: SessionItem.lastMsg.text,
                type: SessionItem.lastMsg.type,
                scene: SessionItem.scene
            }
        })
        for (let i = 0; i < data.length; i++) {
            if (data[i].scene == 'p2p') {
                let paramas = {
                    "userId": Vue.prototype.userId || 0,
                    "targetChatAccount": data[i].to
                }
                let p2pUrl = `${Vue.prototype.NW_API_API_LOCALE_VERSION}/contacts/user/info/get`;
                await Vue.prototype.xurl.postDataJson(p2pUrl, paramas).then((res) => {
                    if (res.success) {
                        data[i].datas = {
                            groupName: res.result.userName,
                            photo: res.result.photoUrl
                        }
                        arr.push(data[i])
                    }
                });
            } else {
                let url = `${Vue.prototype.NW_API_API_LOCALE_VERSION}/contacts/chatGroup/${data[i].to}`;
                await Vue.prototype.xurl.get(url).then(res => {
                    if (res.result) {
                        data[i].datas = res.result
                        arr.push(data[i])
                    }
                })
            }
        }
        state.sessionList = [...arr]

    },
    // 初始化音视频
    initWebrtc (state, obj) {
        console.log('开始初始化 音视频 sdk...')
        let netcall = WebRTC.getInstance({
            container: null, //本端视频展示的容器，不需要初始化的时候赋值
            remoteContainer: null, //远端视频展示的容器，不需要初始化的时候赋值
            chromeId: null, //演示功能是否使用插件
            debug: true,
            nim: state.groupChat.nim,
        })
        state.groupChat.netcall = netcall
        WebRTC.checkCompatibility().then(function (data) {
            console.log('兼容性检查', data)
        })
    },
    //   视频通话的显示
    videoImHidden (state, value) {
        state.videoImHidden = value
    }
}